from datetime import timedelta

from aiogram import Bot, types
from aiogram.filters.callback_data import CallbackData
from aiogram_dialog import DialogManager, StartMode
from arq import ArqRedis
from fluentogram import TranslatorRunner

from weed_shop.core.config import Settings
from weed_shop.core.models.enums.order import OrderStatus
from weed_shop.infrastructure.database.services import OrderService
from weed_shop.tg_bot.services.tg_helpers import delete_msg, send_tg_message
from weed_shop.tg_bot.states import ClientSG, CreateOrderSG, OrderDetailsSG


async def start_order_create(
    call: types.CallbackQuery,
    callback_data: CallbackData,
    dialog_manager: DialogManager,
):
    await delete_msg(call.message)
    is_self_pickup = callback_data.is_self_pickup
    if is_self_pickup:
        await dialog_manager.start(
            CreateOrderSG.select_payment_method,
            data={
                "promocode_id": callback_data.promocode_id,
                "bonuses_amount": callback_data.bonuses_amount,
                "is_self_pickup": callback_data.is_self_pickup,
            },
        )
    else:
        await dialog_manager.start(
            CreateOrderSG.enter_contact_name,
            data={
                "promocode_id": callback_data.promocode_id,
                "bonuses_amount": callback_data.bonuses_amount,
                "is_self_pickup": callback_data.is_self_pickup,
            },
        )


async def go_to_order_handler(
    call: types.CallbackQuery,
    callback_data: CallbackData,
    dialog_manager: DialogManager,
):
    await delete_msg(call.message)
    await dialog_manager.start(
        OrderDetailsSG.order_details,
        data={"order_id": callback_data.order_id},
    )


async def resend_stuff_msg(
    call: types.CallbackQuery,
    dialog_manager: DialogManager,
):
    """Повторно отправляем сообщение сотруднику склада через 5 минут"""

    arq_redis: ArqRedis = dialog_manager.middleware_data.get("arqredis")
    await arq_redis.enqueue_job(
        "notify_user",
        _defer_by=timedelta(seconds=10),
        user_tg_id=call.from_user.id,
        text=call.message.text,
        reply_markup=call.message.reply_markup.model_dump_json(),
    )

    await call.answer()
    await delete_msg(call.message)


async def close_order_handler(
    _,
    callback_data: CallbackData,
    dialog_manager: DialogManager,
):
    """Закрываем заказ пользователя"""

    bot: Bot = dialog_manager.middleware_data.get("bot")
    config: Settings = dialog_manager.middleware_data.get("config")
    locale: TranslatorRunner = dialog_manager.middleware_data.get("locale")
    order_service: OrderService = dialog_manager.middleware_data.get("order_service")

    order_id = callback_data.order_id
    await order_service.update_order_status(order_id, OrderStatus.closed)
    await send_tg_message(
        bot,
        config.tg_bot.admin_channel_id,
        locale.get(
            "order-status-changed-msg",
            order_id=order_id,
            status=OrderStatus.closed.value,
        ),
    )
    await dialog_manager.start(ClientSG.start, mode=StartMode.RESET_STACK)
